package com.zhou.piledriver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhou.piledriver.mapper.PdDeviceRecordMapper;
import com.zhou.piledriver.model.entity.PdDeviceRecord;
import com.zhou.piledriver.model.so.RecordSo;
import com.zhou.piledriver.service.PdDeviceRecordService;
import com.zhou.piledriver.service.PdPileService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ZhouShenBin
 * @date 2024/3/21 9:44
 * @description
 */

@Service
public class PdDeviceRecordServiceImpl implements PdDeviceRecordService {

    @Resource
    private PdDeviceRecordMapper pdDeviceRecordMapper;
    @Resource
    private PdPileService pdPileService;

    @Override
    public Page<PdDeviceRecord> list(Page<PdDeviceRecord> page, RecordSo so) {
        List<Long> pileIds = new ArrayList<>();
        pileIds = pdPileService.listPilesByDevice(so);

        if(CollectionUtils.isEmpty(pileIds)){
            return page;
        }
        LambdaQueryWrapper<PdDeviceRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(PdDeviceRecord::getPileId, pileIds)
                .ge(StringUtils.isNotBlank(so.getStartTime()), PdDeviceRecord::getDataTime, StringUtils.isNotBlank(so.getStartTime()) ? LocalDateTime.parse(so.getStartTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) : null)
                .le(StringUtils.isNotBlank(so.getEndTime()), PdDeviceRecord::getDataTime, StringUtils.isNotBlank(so.getEndTime()) ? LocalDateTime.parse(so.getEndTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) : null)
                .orderByDesc(PdDeviceRecord::getDataTime)
                .orderByDesc(PdDeviceRecord::getId);
        return pdDeviceRecordMapper.selectPage(page, queryWrapper);
    }
}
